package com.example.mylibrary.adapter

import android.content.Context
import android.util.SparseArray
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import androidx.viewbinding.ViewBinding

@Suppress("UNCHECKED_CAST")
abstract class BaseRecyclerAdapter<B : ViewBinding> constructor(val context: Context) :
    RecyclerView.Adapter<BaseRecyclerAdapter<B>.BaseViewHolder>(), View.OnClickListener,
    View.OnLongClickListener {

    lateinit var viewBinding: B

    companion object {
        const val NO_DATA = -1
    }

    var defaultItem: Int = -1
        set(value) {
            field = value
            notifyDataSetChanged()
        }

    private var inflater: LayoutInflater = LayoutInflater.from(context)

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BaseViewHolder {
        viewBinding = getBinding(inflater,parent, viewType)
        val baseViewHolder = BaseViewHolder(viewBinding)
        baseViewHolder.itemView.setOnClickListener(this)
        baseViewHolder.itemView.setOnLongClickListener(this)
        getViewHolder(baseViewHolder)
        return baseViewHolder
    }

    abstract fun getBinding(inflater: LayoutInflater,parent: ViewGroup, viewType: Int): B

    /**
     * 处理点击事件
     */
    open fun getViewHolder(baseViewHolder: BaseViewHolder) {

    }

    override fun onBindViewHolder(holder: BaseViewHolder, position: Int) {
        holder.itemView.tag = position
        holder.itemView.isSelected = defaultItem == position
        bindHolder(holder, position)
    }

    var tempTime = 0L

    /**
     * 点击事件空实现，判断如果点击间隔大于1500秒，执行点击操作，去除连点操作
     */
    override fun onClick(view: View?) {
        val currentTimeMillis = System.currentTimeMillis()
        if (currentTimeMillis - tempTime > 1000) {
            tempTime = currentTimeMillis
            val position = view?.tag as Int
            clickListener?.clickListener(position, view)
        }
    }

    /**
     * 长按点击事件空实现
     */
    override fun onLongClick(view: View?): Boolean {
        val position = view?.tag as Int
        return when (clickListener?.longClickListener(position, view)) {
            false -> false
            else -> true
        }
    }

    /**
     * 绑定控件视图
     */
    abstract fun bindHolder(holder: BaseViewHolder, position: Int)

    interface ClickListener {
        fun clickListener(position: Int, view: View?)
        fun longClickListener(position: Int, view: View?): Boolean
    }

    interface LongClickListener {
        fun longClickListener(position: Int, view: View?): Boolean
    }

    var clickListener: ClickListener? = null

//    var longClickListener: LongClickListener? = null

    /**
     * 内部类Viewholder
     */
    open inner class BaseViewHolder constructor(viewBinding: B) :
        RecyclerView.ViewHolder(viewBinding.root)
}

